// 预加载脚本 - 在主进程中运行，提供安全的IPC通信桥梁
console.log('[Preload] 预加载脚本开始执行');
console.log('[Preload] 当前环境:', typeof window !== 'undefined' ? 'renderer' : 'main');

let contextBridge, ipcRenderer;
try {
    const electron = require('electron');
    contextBridge = electron.contextBridge;
    ipcRenderer = electron.ipcRenderer;
    console.log('[Preload] Electron 模块加载成功');
    console.log('[Preload] contextBridge 类型:', typeof contextBridge);
    console.log('[Preload] ipcRenderer 类型:', typeof ipcRenderer);
} catch (error) {
    console.error('[Preload] Electron 模块加载失败:', error);
    return;
}

console.log('[Preload] contextBridge 可用:', !!contextBridge);
console.log('[Preload] ipcRenderer 可用:', !!ipcRenderer);

// 根据 contextIsolation 状态选择暴露方式
if (contextBridge && ipcRenderer && process.contextIsolated) {
    // 使用 contextBridge 安全地暴露API给渲染进程
    contextBridge.exposeInMainWorld('electronAPI', {
        // Claude 相关API
        checkClaudeCode: () => ipcRenderer.invoke('claude:check-code'),
        getClaudeCodeInfo: () => ipcRenderer.invoke('claude:get-info'),
        getClaudeCodeVersion: () => ipcRenderer.invoke('claude:get-version'),
        testClaudeDetector: () => ipcRenderer.invoke('claude:test-detector'),
        installClaudeCode: () => ipcRenderer.invoke('claude:install-code'),
        validateApiKey: (apiKey) => ipcRenderer.invoke('claude:validate-api-key', apiKey),
        executeTask: (data) => ipcRenderer.invoke('claude:execute-task', data),
        executeClaudeHeadless: (data) => ipcRenderer.invoke('claude:execute-headless', data),
        executeSystemClaude: (data) => ipcRenderer.invoke('claude:execute-system', data),
        
        // Claude 会话管理
        startClaudeSession: (data) => ipcRenderer.invoke('claude:start-session', data),
        executeWithSession: (data) => ipcRenderer.invoke('claude:execute-with-session', data),
        stopClaudeSession: () => ipcRenderer.invoke('claude:stop-session'),
        
        // 存储相关API
        saveApiKey: (apiKey) => ipcRenderer.invoke('storage:save-api-key', apiKey),
        loadApiKey: () => ipcRenderer.invoke('storage:load-api-key'),
        getTaskHistory: (limit) => ipcRenderer.invoke('storage:get-task-history', limit),
        clearCache: () => ipcRenderer.invoke('storage:clear-cache'),
        
        // 工作路径历史管理
        saveWorkspaceTask: (data) => ipcRenderer.invoke('storage:save-workspace-task', data),
        getWorkspaceHistory: (data) => ipcRenderer.invoke('storage:get-workspace-history', data),
        getWorkspaceList: () => ipcRenderer.invoke('storage:get-workspace-list'),
        getWorkspaceListWithStats: () => ipcRenderer.invoke('storage:get-workspace-list-stats'),  // 获取项目列表（历史记录页面用）
        clearWorkspaceHistory: (workPath) => ipcRenderer.invoke('storage:clear-workspace-history', workPath),
        clearAllHistory: () => ipcRenderer.invoke('storage:clear-all-history'),
        
        // 应用相关API
        getAppInfo: () => ipcRenderer.invoke('app:get-info'),
        
        // 文件系统相关API
        selectFolder: () => ipcRenderer.invoke('fs:select-folder'),
        openFolderLocation: (folderPath) => ipcRenderer.invoke('fs:open-folder-location', folderPath),
        
        // 终端相关API
        openTerminalWithClaude: (data) => ipcRenderer.invoke('terminal:open-with-claude', data),
        
        // Claude 可用性检测
        checkClaudeAvailability: (workPath) => ipcRenderer.invoke('claude:check-availability', workPath),
        
        // 流式事件监听
        onStreamData: (callback) => {
            const listener = (event, data) => callback(data);
            ipcRenderer.on('claude:stream-data', listener);
            // 返回清理函数
            return () => ipcRenderer.removeListener('claude:stream-data', listener);
        },
        onStreamComplete: (callback) => {
            const listener = (event, data) => callback(data);
            ipcRenderer.on('claude:stream-complete', listener);
            return () => ipcRenderer.removeListener('claude:stream-complete', listener);
        },
        onStreamError: (callback) => {
            const listener = (event, data) => callback(data);
            ipcRenderer.on('claude:stream-error', listener);
            return () => ipcRenderer.removeListener('claude:stream-error', listener);
        },
        
        // 通用invoke方法
        invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args)
    });

    // 暴露版本信息
    contextBridge.exposeInMainWorld('versions', {
        node: process.versions.node,
        chrome: process.versions.chrome,
        electron: process.versions.electron
    });
    
    console.log('[Preload] 使用 contextBridge 暴露API');
} else if (ipcRenderer) {
    // 当 contextIsolation 为 false 时，直接暴露到 window 对象
    console.log('[Preload] contextIsolation 为 false，直接暴露到 window 对象');
    window.electronAPI = {
        // Claude 相关API
        checkClaudeCode: () => ipcRenderer.invoke('claude:check-code'),
        getClaudeCodeInfo: () => ipcRenderer.invoke('claude:get-info'),
        getClaudeCodeVersion: () => ipcRenderer.invoke('claude:get-version'),
        testClaudeDetector: () => ipcRenderer.invoke('claude:test-detector'),
        installClaudeCode: () => ipcRenderer.invoke('claude:install-code'),
        validateApiKey: (apiKey) => ipcRenderer.invoke('claude:validate-api-key', apiKey),
        executeTask: (data) => ipcRenderer.invoke('claude:execute-task', data),
        executeClaudeHeadless: (data) => ipcRenderer.invoke('claude:execute-headless', data),
        executeSystemClaude: (data) => ipcRenderer.invoke('claude:execute-system', data),
        
        // Claude 会话管理
        startClaudeSession: (data) => ipcRenderer.invoke('claude:start-session', data),
        executeWithSession: (data) => ipcRenderer.invoke('claude:execute-with-session', data),
        stopClaudeSession: () => ipcRenderer.invoke('claude:stop-session'),
        
        // 存储相关API
        saveApiKey: (apiKey) => ipcRenderer.invoke('storage:save-api-key', apiKey),
        loadApiKey: () => ipcRenderer.invoke('storage:load-api-key'),
        getTaskHistory: (limit) => ipcRenderer.invoke('storage:get-task-history', limit),
        clearCache: () => ipcRenderer.invoke('storage:clear-cache'),
        
        // 工作路径历史管理
        saveWorkspaceTask: (data) => ipcRenderer.invoke('storage:save-workspace-task', data),
        getWorkspaceHistory: (data) => ipcRenderer.invoke('storage:get-workspace-history', data),
        getWorkspaceList: () => ipcRenderer.invoke('storage:get-workspace-list'),
        getWorkspaceListWithStats: () => ipcRenderer.invoke('storage:get-workspace-list-stats'),  // 获取项目列表（历史记录页面用）
        clearWorkspaceHistory: (workPath) => ipcRenderer.invoke('storage:clear-workspace-history', workPath),
        clearAllHistory: () => ipcRenderer.invoke('storage:clear-all-history'),
        
        // 应用相关API
        getAppInfo: () => ipcRenderer.invoke('app:get-info'),
        
        // 文件系统相关API
        selectFolder: () => ipcRenderer.invoke('fs:select-folder'),
        openFolderLocation: (folderPath) => ipcRenderer.invoke('fs:open-folder-location', folderPath),
        
        // 终端相关API
        openTerminalWithClaude: (data) => ipcRenderer.invoke('terminal:open-with-claude', data),
        
        // Claude 可用性检测
        checkClaudeAvailability: (workPath) => ipcRenderer.invoke('claude:check-availability', workPath),
        
        // 流式事件监听
        onStreamData: (callback) => {
            const listener = (event, data) => callback(data);
            ipcRenderer.on('claude:stream-data', listener);
            // 返回清理函数
            return () => ipcRenderer.removeListener('claude:stream-data', listener);
        },
        onStreamComplete: (callback) => {
            const listener = (event, data) => callback(data);
            ipcRenderer.on('claude:stream-complete', listener);
            return () => ipcRenderer.removeListener('claude:stream-complete', listener);
        },
        onStreamError: (callback) => {
            const listener = (event, data) => callback(data);
            ipcRenderer.on('claude:stream-error', listener);
            return () => ipcRenderer.removeListener('claude:stream-error', listener);
        },
        
        // 通用invoke方法
        invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args)
    };

    // 暴露版本信息
    window.versions = {
        node: process.versions.node,
        chrome: process.versions.chrome,
        electron: process.versions.electron
    };
} else {
    console.error('[Preload] ipcRenderer 不可用，无法暴露API');
}

console.log('[Preload] API 暴露完成');
console.log('[Preload] electronAPI 已暴露:', !!window.electronAPI);
console.log('[Preload] versions 已暴露:', !!window.versions);

